<template>
  <section class="wrap">
    <el-form ref="queryFormRef" :model="queryForm" :inline="true">
      <el-tabs v-model="queryForm.activeTab" @tab-click="handleClickTab">
        <el-tab-pane label="客户基本信息" name="customInfo">
          <el-form-item label="客户姓名:" prop="custName">
            <el-input v-model="queryForm.custName" style="width:200px" clearable placeholder="请输入客户名称"
              @keyup.enter="getList"></el-input>
          </el-form-item>
          <el-form-item label="客户ID:" prop="custID">
            <el-input v-model="queryForm.custID" style="width:200px" clearable placeholder="请输入客户ID"
              @keyup.enter="getList"></el-input>
          </el-form-item>
          <el-form-item label="客户昵称:" prop="nickName">
            <el-input v-model="queryForm.nickName" style="width:200px" clearable placeholder="请输入客户昵称"
              @keyup.enter="getList"></el-input>
          </el-form-item>
          <el-form-item label="客户手机:" prop="phoneNo" v-if="userRole !=3">
            <el-input v-model="queryForm.phoneNo" style="width:200px" clearable placeholder="请输入客户手机号"
              @keyup.enter="getList"></el-input>
          </el-form-item>
          <el-form-item label="客户微信:" prop="wx"  v-if="userRole !=3">
            <el-input v-model="queryForm.wx" style="width:200px" clearable placeholder="请输入客户微信号"
              @keyup.enter="getList"></el-input>
          </el-form-item>
          <el-form-item label="客户邮箱:" prop="email" v-if="userRole !=3">
            <el-input v-model="queryForm.email" style="width:200px" clearable placeholder="请输入客户邮箱"
              @keyup.enter="getList"></el-input>
          </el-form-item>
          <br/>
          <el-form-item label="渠道:" prop="qdName" v-if="userRole == 1 && cusqdsMap.length">
            <el-select v-model="queryForm.qdName" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in cusqdsMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务员:" prop="salesID" v-if="userRole == 1 && salesMap.length">
            <el-select v-model="queryForm.salesID" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in salesMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务员结算:" prop="salesIsGive" v-if="userRole == 1">
            <el-select v-model="queryForm.salesIsGive" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.giveStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="推荐人:" prop="referrerID" v-if="userRole == 1 && referrersMap.length">
            <el-select v-model="queryForm.referrerID" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in referrersMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="推荐结算:" prop="referrerIsGive" v-if="userRole == 1">
            <el-select v-model="queryForm.referrerIsGive" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.giveStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          
        </el-tab-pane>


        <el-tab-pane label="客户状态" name="documentStatus">
          <el-form-item label="资料状态:" prop=".documentStatus">
            <el-select v-model="queryForm.documentStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in  DeviceUtils.documentStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>  
          <el-form-item label="面试状态:" prop="interviewStatus">
            <el-select v-model="queryForm.interviewStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.interviewStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="批文状态:" prop="visaStatus">
            <el-select v-model="queryForm.visaStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.visaStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="保险状态:" prop="insuranceStatus">
            <el-select v-model="queryForm.insuranceStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.insuranceStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="入境卡状态:" prop="entranceCardStatus">
            <el-select v-model="queryForm.entranceCardStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.entranceCardStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="入境状态:" prop="entryStatus">
            <el-select v-model="queryForm.entryStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.entryStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="入职状态:" prop="shopId">
            <el-select v-model="queryForm.employmentStatus" placeholder="请选择" @change="getList">
              <el-option label="全部" value="" />
              <el-option v-for="item in DeviceUtils.employmentStatusMap" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      
      <el-form-item label="时间选择:" prop="time">
        <el-date-picker v-model="queryForm.time" type="datetimerange" :shortcuts="shortcuts" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" align="right">
        </el-date-picker>
      </el-form-item>

      <div>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
          <el-button v-if="userRole == 1 || userRole == 2" type="primary" @click="handleCreateCustom">添加客户</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table :data="page.list" v-loading="page.loading" element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.6)" ref="table"
      style="width: 100%">
      <el-table-column label="客户ID" prop="custID"></el-table-column>
      <el-table-column label="客户名称" prop="custName"></el-table-column>
      <el-table-column label="客户昵称" prop="nickName"></el-table-column>
      <el-table-column label="客户手机" prop="phoneNo" v-if="userRole == 1"></el-table-column>
      <el-table-column label="客户微信" prop="wx" v-if="userRole == 1"></el-table-column>
      <el-table-column label="客户邮箱" prop="email" v-if="userRole == 1"></el-table-column>
      <el-table-column label="销售ID" prop="salesID" v-if="userRole == 1"></el-table-column>
      <el-table-column label="销售名称" prop="salesName" v-if="userRole == 1"></el-table-column>
      <el-table-column label="推荐人ID" prop="referrerID"></el-table-column>
      <el-table-column label="推荐人名称" prop="referrerName"></el-table-column>
      <el-table-column label="渠道" prop="qd_name"></el-table-column>
      <el-table-column label="资料状态" prop="documentStatus">
        <template #default="scope">
          {{getStatusText('documentStatusMap', scope.row.documentStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="面试状态" prop="interviewStatus">
        <template #default="scope">
          {{getStatusText('interviewStatusMap', scope.row.interviewStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="批文状态" prop="visaStatus">
        <template #default="scope">
          {{getStatusText('visaStatusMap', scope.row.visaStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="保险状态" prop="insuranceStatus">
        <template #default="scope">
          {{getStatusText('insuranceStatusMap', scope.row.insuranceStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="入境卡状态" prop="entranceCardStatus">
        <template #default="scope">
          {{getStatusText('entranceCardStatusMap', scope.row.entranceCardStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="入境状态" prop="entryStatus">
        <template #default="scope">
          {{getStatusText('entryStatusMap', scope.row.entryStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="入职状态" prop="employmentStatus">
        <template #default="scope">
          {{getStatusText('employmentStatusMap', scope.row.employmentStatus )}}
        </template>
      </el-table-column>
      <el-table-column label="业务员结算" prop="employmentStatus" v-if="userRole == 1">
        <template #default="scope">
          {{getStatusText('giveStatusMap', scope.row.salesIsGive )}}
        </template>
      </el-table-column>
      <el-table-column label="推荐人结算" prop="employmentStatus" v-if="userRole == 1">
        <template #default="scope">
          {{getStatusText('giveStatusMap', scope.row.referrerIsGive )}}
        </template>
      </el-table-column>
      <el-table-column label="添加时间" prop="createAt">
        <template #default="scope">
          {{formatTimeText(scope.row.createAt )}}
        </template>
      </el-table-column>
      <el-table-column
        v-if="userRole == 1 || userRole ==2"
        fixed="right"
        label="操作"
        width="160"
      >
        <template #default="scope">
          <el-button v-if="userRole == 1 || userRole ==2" type="text" @click="handleEditCustom(scope.row)">编辑</el-button>
          <el-button v-if="userRole == 1 || userRole ==2" type="text" @click="handleShowCustomVisit(scope.row)">沟通记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNum" :page-size="page.pageSize"
        :page-sizes="[25, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
      </el-pagination>
    </div>

    <editCustom 
      v-if="showEditCustom"
      :showDialog="showEditCustom"
      :currentRow="currentRow"
      :salesMap="salesMap"
      :referrersMap="referrersMapPop"
      :cusqdsMap="cusqdsMap"
      @close="disVisibleForm"
      @success="setSuccess"
    >
    </editCustom>
    <visit
      v-if="showVisit"
      :showDialog="showVisit"
      :currentRow="currentRow"
      @close="disVisibleForm"
    >
    </visit>
  </section>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter, } from "vue-router"
import { ElMessage, ElMessageBox } from "element-plus";
import moment from 'moment'
import * as DeviceUtils from "./utils";
import {customList, getAccounts, getCusqd } from './api.js'

import editCustom from './components/editCustom.vue'
import visit from './components/visit.vue'

const userRole = window.localStorage.getItem('login_role') || 1

const getStatusText = (statusMap, status) => {
  if (DeviceUtils[statusMap]) {
    let index =  DeviceUtils[statusMap].findIndex(item=> item.value == status)
    if (index > -1) {
      return DeviceUtils[statusMap][index].label
    } else {
      return '-'
    }
  }
}

const formatTimeText = (time) => {
  if (time < 10000000000) {
    time = time * 1000
  }
  return moment(time).format('YYYY-MM-DD HH:mm:ss')
}

const router = useRouter()

const queryFormRef = ref(null)
const queryForm = reactive({
  activeTab: "customInfo",

  custName: "",
  custID: "",
  nickName: "",
  referrerID: "",
  documentStatus: "",
  interviewStatus: "",
  visaStatus: "",
  insuranceStatus: "",
  entranceCardStatus: "",
  entryStatus: "",
  employmentStatus: "",
  phoneNo: "",
  email: "",
  salesID: "",

  wx: "",
  salesIsGive: "",
  referrerIsGive: "",

  time: [],
  addStartTime: "",
  addEndTime: "",

  qdName: ""
})

const shortcuts = [
  {
    text: '最近一天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 1)
      return [start, end]
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  }
]

const productList = reactive([])

const page = reactive({
  list: [],
  total: 0,
  pageNum: 1,
  pageSize: 25,
  loading: false,
});
let showEditCustom = ref(false)
let showVisit = ref(false)
let currentRow = ref({})


// 查询客服列表
const getList = async () => {
  const params = {
    // page: page.pageNum,
    // size: page.pageSize
  }

  for (let key in queryForm) {
    if (queryForm[key]) {
      let exCludesKey = ['time', 'activeTab']
      if (!exCludesKey.includes(key) && queryForm[key]) {
        params[key] = queryForm[key]
      }
    }
  }

  if (queryForm.time.length) {
    params.addStartTime = new Date(queryForm.time[0]).getTime()
    params.addEndTime = new Date(queryForm.time[1]).getTime()
  }

  page.loading = true
  page.list = []
  const res = await customList(params)
  if (0 === res.status) {
    if (res && res.data) {
      let result = res.data.list
      page.list = result
      page.total = res.data.count
    }
  }
  page.loading = false
}

const handleClickTab = () => {

}

const handleCreateCustom = () => {
  currentRow = {}
  showEditCustom.value = true
}

const handleEditCustom = (row) => {
  currentRow = row
  showEditCustom.value = true
}

const handleShowCustomVisit = (row) => {
  currentRow = row
  showVisit.value = true
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  page.list = []
}

const disVisibleForm = () => {
  showEditCustom.value = false
  showVisit.value = false
}

const setSuccess = () => {
  getList()
}

const handleSizeChange = (val) => {
  page.pageSize = val;
  page.pageNum = 1;
  getList();
};

const handleCurrentChange = (val) => {
  page.pageNum = val;
  getList();
};

getList()

let salesMap = ref([])
let referrersMap = ref([])
let referrersMapPop = ref([])
let cusqdsMap = ref([])

const getAccountsFn = async (role) => {
  const res = await getAccounts({
    role
  })
  if (res.status == 0) {
    let arr = []
    res.data.forEach(item => {
      arr.push({
        label: item.nickName,
        value: item.id
      })
    });
    if (role == 2) {
      salesMap.value = arr
    } else if (role == 3) {
      referrersMap.value = arr
      let newArr = arr.slice(0, arr.length)
      newArr.pop()
      referrersMapPop.value = newArr
    } 
  }
}

const getCusqdFn = async () => {
  const res = await getCusqd({})
  if (res.status == 0) {
    let arr = []
    res.data.forEach(item => {
      arr.push({
        label: item.name,
        value: item.name
      })
    });
    cusqdsMap.value = arr
  }
}

getAccountsFn(2)
getAccountsFn(3)
getCusqdFn()
</script>
<style lang="scss" scoped>
@import url('./index.scss');
</style>